<template>
  <el-upload
    class="upload-demo"
    drag
    action="http://192.168.88.250:8000/api/vpn/upload"
    multiple
    accept=".txt"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">拖拽文件或者 <em>点击选择文件上传</em></div>
    <template #tip>
      <div class="el-upload__tip">
        只能上传txt格式文件, 数据格式IP|端口|用户名|密码
      </div>
    </template>
  </el-upload>

  <el-table :data="tableData" border stripe style="width: 100%">
    <el-table-column prop="id" label="ID" width="100" />
    <el-table-column prop="fileName" label="文件名" />
    <el-table-column prop="count" label="数量" sortable />
    <el-table-column prop="transientField" label="是否用完就删">
      <template #default="scope">
        <el-switch
          v-model="scope.row.transientField"
          @click="handelTransientFieldClick(scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column prop="startUsing" label="是否启用">
      <template #default="scope">
        <el-switch
          v-model="scope.row.startUsing"
          @click="handelStartUsingClick(scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          type="danger"
          size="small"
          @click.prevent="deleteRow(scope.row.fileName)"
        >
          清空
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
  
  <script setup>
import { ref, onMounted } from "vue";
const tableData = ref([]);
import { getList, runAndRemove, deleteVPN } from "../api/vpn";
import { ElMessage } from "element-plus";

const getVPNlist = async () => {
  const response = await getList();
  if (response && response.data) {
    tableData.value = response.data.map((item, index) => {
      return {
        id: index,
        fileName: item.fileName,
        count: item.count,
        transientField: item.transientField === 1 ? true : false,
        startUsing: item.startUsing === 1 ? true : false,
      };
    });
  }
};
onMounted(() => {
  getVPNlist();
});

const handelTransientFieldClick = async (value) => {
  const response = await runAndRemove(
    value.fileName,
    "transientField",
    value.transientField
  );
  ElMessage({
    message: response.message,
    type: "success",
  });
};
const handelStartUsingClick = async (value) => {
  const response = await runAndRemove(
    value.fileName,
    "startUsing",
    value.transientField
  );
  ElMessage({
    message: response.message,
    type: "success",
  });
};

const deleteRow = async (fileName) => {
  const response = await deleteVPN(fileName);
  ElMessage({
    message: response.message,
    type: "success",
  });
  getVPNlist();
};
</script>
  